package com.example.twitter;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import twitter4j.User;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TweetAdapter extends BaseAdapter {
	
	protected Activity miActivity;
	protected ArrayList<TweetPerson> tweets;
	
	public TweetAdapter(Activity a, ArrayList<TweetPerson> t){
		miActivity = a;
		tweets = t;
	}

	@Override
	public int getCount() {
		return tweets.size();
	}

	@Override
	public Object getItem(int arg0) {
		return tweets.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		
		return tweets.get(arg0).getId();
	}

	@Override
	public View getView(int arg0, View convertView, ViewGroup arg2) {
		View vi = convertView;
		
		if(convertView == null){
			LayoutInflater inflater = (LayoutInflater) miActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    vi = inflater.inflate(R.layout.list_tweet_layout, null);
		    
		}
		
		TweetPerson tweet = tweets.get(arg0);
		User user = tweet.getUsuario();
		
		ImageView imagen = (ImageView) vi.findViewById(R.id.imageViewImagenUser);
		TextView txScreenName = (TextView) vi.findViewById(R.id.textViewScreen);
		txScreenName.setText("@" + user.getScreenName());
		TextView txUser = (TextView) vi.findViewById(R.id.textViewUser);
		txUser.setText(user.getName());
		TextView txTexto = (TextView) vi.findViewById(R.id.textViewText);
		txTexto.setText(tweet.getTexto());
		
		
		
		
		URL url = null;
		
		try {
			url = new URL(user.getProfileImageURL());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		InputStream input = null;
		
		try {
			input = (InputStream) url.getContent();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Drawable d = Drawable.createFromStream(input, null);
		imagen.setImageDrawable(d);
		
		
		
		return vi;
	}

}
